import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTabbedPane;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.plaf.basic.BasicTabbedPaneUI;

import CustomSwing.JCLabel;
import CustomSwing.JCTextField;

@SuppressWarnings("serial")
public class MainFrame extends JFrame {
	private static final int APP_WIDTH = 780;
	private static final int APP_HEIGHT = 550;
	
	private Db db = new Db();
	private Font custFont = new Font("Arial Bold", Font.BOLD, 14);
	private final Border border = BorderFactory.createMatteBorder(3, 3, 3, 3, Color.BLACK);

	private final JPanel mainPanel = new JPanel(new BorderLayout());
	private final JTabbedPane tabbedPane = new JTabbedPane();
	
	private VendorSalesPanel vsPanel;
	private MarketTotalsPanel mtPanel;
	private ListOfVendorsPanel lovPanel;
	private VendorInfoPanel viPanel;
	private CreateNewVendorPanel cnvPanel;
	private VendorCountPanel vcPanel;
	private OutstandingTransPanel otPanel;
	private NotesPanel nPanel;
	
	private JCTextField unTF = new JCTextField("root");
	private JPasswordField pwTF = new JPasswordField("");
	private JCTextField sTF = new JCTextField("localhost:3306");
	private JCTextField dbTF = new JCTextField("farmersmarketdb");
	
	public MainFrame() {
		super("Farmer's Market Manager Tool");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setSize(APP_WIDTH, APP_HEIGHT);
		setLocationRelativeTo(null);
	}

	public void start() {
		login();
		add(mainPanel);
		setVisible(true);
	}
	
	private void login() {
		JPanel loginPanel = new JPanel(new GridLayout(5, 2, 5, 5));
		loginPanel.setBorder( BorderFactory.createCompoundBorder(
				BorderFactory.createMatteBorder(1, 1, 1, 1, Color.BLACK), 
				BorderFactory.createEmptyBorder(5, 5, 5, 5)));
		loginPanel.add(new JCLabel("Username"));
		loginPanel.add(unTF);
		loginPanel.add(new JCLabel("Password"));
		loginPanel.add(pwTF);
		loginPanel.add(new JCLabel("Server"));
		loginPanel.add(sTF);
		loginPanel.add(new JCLabel("Database"));
		loginPanel.add(dbTF);
		loginPanel.add(createButton("Login"));
		loginPanel.add(createButton("Exit"));
		
		JPanel loginPanelHolder = new JPanel(new GridBagLayout());
		loginPanelHolder.add(loginPanel);
		
		mainPanel.add(loginPanelHolder);
	}

	private void createMenuBar() {
		JMenu file = new JMenu("File");
		file.add(createMenuItem("Exit"));

		JMenu options = new JMenu("Options");
		options.add(createMenuItem("Market Settings"));

		JMenu help = new JMenu("Help");
		help.add(createMenuItem("About"));

		JMenuBar menuBar = new JMenuBar();
		menuBar.add(file);
		menuBar.add(options);
		menuBar.add(help);

		setJMenuBar(menuBar);
	}

	private JMenuItem createMenuItem(final String name) {
		JMenuItem item = new JMenuItem(name);
		item.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (name.equalsIgnoreCase("Exit")) {
					System.exit(0);
				} else if (name.equalsIgnoreCase("Market Settings")) {
					showMarketSettings();
				} else if (name.equalsIgnoreCase("About")) {
					JPanel aboutPanel = new JPanel(new GridLayout(5, 1, 3, 3));
					aboutPanel.add(new JCLabel("Farmer's Market Manager Tool"));
					aboutPanel.add(new JCLabel(""));
					aboutPanel.add(new JLabel("Steve Hipolito"));
					aboutPanel.add(new JLabel("Abraham Santini"));
					aboutPanel.add(new JLabel("Daniel Beraun"));
					JOptionPane.showConfirmDialog(null, aboutPanel, 
							"About", JOptionPane.CLOSED_OPTION); 
				}
			}
		});
		return item;
	}

	private void showMarketSettings() {
		JCTextField mrTF = createSettingTF("mr");
		JCTextField scTF = createSettingTF("sc");

		JPanel mrPanel = new JPanel(new GridLayout(2, 2, 5, 5));
		mrPanel.add(new JCLabel("Market rate: "));
		mrPanel.add(mrTF);
		mrPanel.add(new JCLabel("Stall cost: "));
		mrPanel.add(scTF);

		final int value = JOptionPane.showConfirmDialog(this, mrPanel, 
				"Market Settings", JOptionPane.OK_CANCEL_OPTION); 

		try {
			if (value == JOptionPane.OK_OPTION) {
				if (!isDouble(mrTF.getText().trim()) || !isDouble(scTF.getText().trim())) {
					JOptionPane.showConfirmDialog(null, "Input numbers only", 
							"Error", JOptionPane.CLOSED_OPTION); 
					showMarketSettings();
				} else {
					db.setMarketStallFee(mrTF.getText().trim(), scTF.getText().trim(), "1");
					refresh();
				}		
			}
		} catch (SQLException e) { e.printStackTrace();
		} catch (ClassNotFoundException e) { e.printStackTrace(); }
	}
	
	private JCTextField createSettingTF(final String setting) {
		JCTextField tf = new JCTextField("");
		tf.setFont(custFont);
		Double stallCost = 0.0;
		Double marketRate = 0.0;
		try {
			stallCost = Double.parseDouble(db.getStallFee("1"));
			marketRate = Double.parseDouble(db.getMarketFee("1"));
			if (setting.equals("mr")) {
				tf.setText(""+marketRate);
			} else if (setting.equals("sc")) {
				tf.setText(""+stallCost);
			}
		} catch (ClassNotFoundException e1) {
		} catch (SQLException e1) {}		
		return tf;
	}

	private void createTabs() {
		tabbedPane.add(tab(vsPanel, vsPanel.USER_FUNC), vsPanel.USER_FUNC);
		tabbedPane.add(tab(mtPanel, mtPanel.USER_FUNC), mtPanel.USER_FUNC);
		tabbedPane.add(tab(lovPanel, lovPanel.USER_FUNC), lovPanel.USER_FUNC);
		tabbedPane.add(tab(viPanel, viPanel.USER_FUNC), viPanel.USER_FUNC);
		tabbedPane.add(tab(cnvPanel, cnvPanel.USER_FUNC), cnvPanel.USER_FUNC);
		tabbedPane.add(tab(vcPanel, vcPanel.USER_FUNC), vcPanel.USER_FUNC);
		tabbedPane.add(tab(otPanel, otPanel.USER_FUNC), otPanel.USER_FUNC);
		tabbedPane.add(tab(nPanel, nPanel.USER_FUNC), nPanel.USER_FUNC);

		tabbedPane.setUI(new BasicTabbedPaneUI() {
			@Override
			protected void installDefaults() {
				super.installDefaults();
				highlight = Color.black;
				lightHighlight = Color.black;
				shadow = Color.white;
				darkShadow = Color.black;
				focus = Color.black;
			}
		});
		tabbedPane.setBackground(Color.LIGHT_GRAY);
		tabbedPane.setSelectedIndex(2);
		tabbedPane.setFont(custFont);
		tabbedPane.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent arg0) {
				refresh();
			}
		});
		
		mainPanel.add(tabbedPane);
	}
	
	private void refresh() {
		TabPanel panel = (TabPanel) tabbedPane.getSelectedComponent();
		if (panel.name.equals(vsPanel.USER_FUNC))
			vsPanel.refreshComboBox();
		if (panel.name.equals(viPanel.USER_FUNC))
			viPanel.refreshComboBox();
		if (panel.name.equals(mtPanel.USER_FUNC))
			mtPanel.refreshTablePanel();
		if (panel.name.equals(lovPanel.USER_FUNC))
			lovPanel.refreshTablePanel();
		if (panel.name.equals(otPanel.USER_FUNC))
			otPanel.refreshTablePanel();
	}

	private TabPanel tab(JPanel panel, String ufName) {
		JPanel ufTitlePanel = new JPanel();
		ufTitlePanel.setBorder(BorderFactory.createMatteBorder(0, 0, 3, 0, Color.BLACK));
		ufTitlePanel.add(new JCLabel("-  "+ufName+"  -"));

		TabPanel tab = new TabPanel(new BorderLayout(), ufName);
		tab.setBorder(border);
		panel.setBorder(BorderFactory.createEmptyBorder(10, 5, 5, 5));
		tab.add(panel);
		tab.add(ufTitlePanel, BorderLayout.NORTH);

		return tab;
	}
	
	private JButton createButton(final String name) {
		JButton button = new JButton(name);
		button.setFont(custFont);
		button.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent ae) {
				if (name.equalsIgnoreCase("Login")) {
					if(db.setDB(unTF.getText(), pwTF.getText(), 
        							sTF.getText(), dbTF.getText())) {
        					vsPanel = new VendorSalesPanel(db);
        					mtPanel = new MarketTotalsPanel(db);
        					lovPanel = new ListOfVendorsPanel(db);
        					viPanel = new VendorInfoPanel(db);
        					cnvPanel = new CreateNewVendorPanel(db);
        					vcPanel = new VendorCountPanel(db);
        					otPanel = new OutstandingTransPanel(db);
        					nPanel = new NotesPanel();
        					mainPanel.removeAll();
        					createMenuBar();
        					createTabs();
        					mainPanel.repaint();
        					mainPanel.revalidate();
					} else {
						JOptionPane.showConfirmDialog(null, "No connection", 
								"Error", JOptionPane.CLOSED_OPTION); 
					}
				} else if (name.equalsIgnoreCase("Exit")) {
					System.exit(0);
				}
			}
		});
		return button;
	}
	
	private boolean isDouble(String s) {
		try { Double.parseDouble(s); 
		} catch(NumberFormatException e) { return false; }
		return true;
	}

	private class TabPanel extends JPanel {
		public String name;
		public TabPanel(LayoutManager layout, String name) {
			this.name = name;
			setLayout(layout);
		}
	}

	public static void main(String... args) {
		new MainFrame().start();
	}
}
